package com.adminserver.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import com.adminserver.mapper.RepairOrdersMapper;
import com.adminserver.service.RepairOrdersService;
import com.adminserver.util.DateGenerator.DateGenerator;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    RepairOrdersMapper repairOrdersMapper;

    @Autowired
    RepairOrdersService repairOrdersService;

    @PostMapping("/pullOrderList")
    public ResponseUtil pullOrderList(@RequestBody(required = false) Map<String, String> map) {
        String[] years = new String[2];
        if (ObjectUtil.isEmpty(map)) {
            years = DateGenerator.getYearBeginEndTime(DateUtil.date().year());
        }else{
            years[0] = map.get("beginRepairDate");
            years[1] = map.get("endRepairDate");
        }
        return ResponseUtil.setE(ResponseEnum.OK).setData(repairOrdersMapper.queryAllByRepairDateBetween(years[0], years[1]));
    }

    @Transactional
    @PostMapping("/delOrders")
    public ResponseUtil delOrders(@RequestBody String [] orderIds){
        Console.log(orderIds);
        // 删除订单
        try{
            repairOrdersService.removeByIds(Arrays.asList(orderIds));
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("有 "+(orderIds.length)+" 笔订单删除成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单删除失败，请稍候再试");
        }
    }
}
